###
### estimate differential tune-out induced by political ads over time
###

library(tidyverse)
library(parallel)
library(lubridate)
library(hms)
library(broom)
library(ggthemes)
library(data.table)
library(magrittr)

### SET WORKING DIRECTORY HERE ###
path_to_archive <- "replication/"
data_dir <- paste0(path_to_archive, "data/")
setwd(data_dir)
plot_dir <- paste0(path_to_archive, "plots/")
tables_dir <- paste0(path_to_archive, "tables/")


load(paste0(data_dir, "ads_dd_tuneout_all.RData"))

### analysis and plots ###

tuneout_rate <- tuneout_all %>% 
	as.data.table %>%
	.[n_t > 0] %>%
	.[,`:=` (ad_tuneout_frac = tuneout_real / n_t, random_tuneout_frac = tuneout_random / n_t)] %>%
	.[,.(dma_code, channel, affiliate, program, event_time_utc, n_t, ad_tuneout_frac, random_tuneout_frac)] %>%
	melt(id.vars = c("dma_code", "channel", "affiliate", "program", "event_time_utc", "n_t"), measure_vars = c("random_tuneout_frac", "ad_tuneout_frac"), variable.name = "Type", value.name = "tune_out") %>%
	.[,Type := if_else(Type == "ad_tuneout_frac", "Ad", "Random")]

overall_avg <- tuneout_rate[,.(Mean=sum(tune_out*n_t)/sum(n_t)), by =.(Type)]

mean_label <- paste("Mean Tune-out Rates\n", paste(overall_avg$Type, ": ", round(overall_avg$Mean,3), sep = "", collapse="\n"), sep="")

### FIGURE E.1
theme_set(theme_few())

ggplot(aes(x=tune_out, group=Type), data=tuneout_rate) + 
	geom_density(aes(fill = Type, weight = n_t), alpha=0.5) + 
	annotate("label", label = mean_label, x=0.2, y = 17, hjust=1) + 
	scale_colour_brewer(palette="Set2") + 
	xlim(0,0.25) +
	labs(x="Fraction Tuning Out", y = "Weighted Density")

ggsave(filename=paste0(data_dir, "tune_out.pdf"), height=7, width=10)



